<template>
  <el-scrollbar :native="false" class="subtitle-fix">
    <div class="file-select">
      <div class="file-area">
        
        <span><span>点击</span><el-button type="primary" size="mini" icon="el-icon-plus" @click="chooseFile">选择文件</el-button></span>

      </div>
    </div>
    <table class="list-table">
      <thead>
      <tr>
        <td width="30%">查找内容</td>
        <td width="30%">替换内容</td>
        <td></td>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td><el-input v-model="findstr" placeholder=""></el-input></td>
        <td><el-input v-model="replacestr" placeholder=""></el-input></td>
        <td><el-button type="success" size="mini" icon="el-icon-download"
                     @click="doFix" :disabled="fileList.length < 1">批量替换</el-button></td>
      </tr>
      
      </tbody>
    </table>
    <div class="result">
      <div style="width: 96%;">共计替换{{totalCount}}次</div>
      <textarea v-model="logStr"></textarea>
    </div>
  </el-scrollbar>
</template>

<script>
import fs from 'fs'
import _path from 'path'

export default {
  name: 'SubtitleFix',
  data () {
    return {
      fileList: [],
      findstr: '',
      replacestr: '',
      logStr: '',
      totalCount: 0
    }
  },
  watch: {},
  created () {
    console.log(`${this.$options.name} created`)
  },
  mounted () {
    console.log(`${this.$options.name} mounted`)
  },
  methods: {
    doFix() {
      this.totalCount = 0
      this.logStr = ''
      
      this.logStr += `共有文件${this.fileList.length}个，批量替换【${this.findstr}】->【${this.replacestr}】\n`
      this.fileList.forEach(it => {
        const filePath = it.path

        // 读取文件
        fs.readFile(filePath, 'utf8', (err, data) => {
          let replaceCount = 0
          this.logStr += `读取文件【${filePath}】\n`
          if (err) {
            console.error('读取文件时出错:', err);
            return;
          }

          // 使用全局正则表达式替换所有匹配项
          let modifiedData = data.replace(new RegExp(this.findstr, 'g'), (match) => {
            replaceCount++; // 每次匹配时增加计数
            this.totalCount++
            return this.replacestr;
          });
          this.logStr += `替换内容【${filePath}】【${this.findstr}】【${this.replacestr}】【${replaceCount}】次\n`

          // 写回文件
          fs.writeFile(filePath, modifiedData, 'utf8', (err) => {
            if (err) {
              console.error('写入文件时出错:', err);
              return;
            }
            this.logStr += `修改成功【${filePath}】\n`
          });
        });
          
      })
    },
    chooseFile () {
      this.$electron.remote.dialog.showOpenDialog({
        filters: [
          {name: 'Subtitle', extensions: ['ass']}
        ],
        properties: [
          'openFile',
          'multiSelections'
        ]
      }).then(result => {
        let fileList = []
        result.filePaths.forEach(it => {
          let fileStat = fs.statSync(it)
          fileList.push({
            name: _path.basename(it),
            size: fileStat.size,
            path: it
          })
        })
        this.fileList = fileList
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.subtitle-fix{
  width: 100%;
  height: 100%;
  .file-select {
    display: flex;
    align-items: center;
    justify-content: center;

    .file-area {
      margin: 20px;
      width: 200px;
      height: 200px;
      background-color: #eee;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      border: 4px dashed gray;
    }

    .file-area.dragoverClass {
      border: 4px dashed limegreen;
    }
  }

  .list-table{
    margin-left: 2%;
    width: 96%;
  }

  .result{
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    textarea{
      width: 96%;
      height: 300px;
      resize: none;
    }
  }
}



</style>
